<?php

/**
 * Desc: 登录控制器
 * Created by chenxinxing
 * Date: 2018-08-14
 */

namespace App\Http\WechatAuth\Controllers;

use App\Http\WechatAuth\Models\User;
use App\Api\BaseClass\Controller;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Http\Request;
use App\Http\Requests;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Session\Store as SessionStore;
use Illuminate\Http\Concerns\InteractsWithFlashData;
use App\Http\WechatAuth\Models\WebUserToken;
use Illuminate\Support\Str;
use App\Http\WechatAuth\Classes\Token;

class SignController extends Controller
{
    private $userService;
    private $tokenService;

    public function __construct()
    {
        parent::__construct();
        session_start();
        $this->userService = new User();
        $this->tokenService = new Token();
    }

    /**
     * 图形验证码生成
     * @param  [type] $tmp [description]
     * @return [type]      [description]
     */
    public function captcha()
    {
        // 生成验证码图片的Builder对象，配置相应属性
        $builder = new CaptchaBuilder;
        // 可以设置图片宽高及字体
        $builder->build($width = 180, $height = 70, $font = null);
        // 获取验证码的内容
        $phrase = $builder->getPhrase();
        
        // 把内容存入session        
        $_SESSION['info'] = $phrase;
        // dd($_SESSION['info']);
        // 生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();
    }

    /**
     * 登录
     */
    public function sign()
    {
        $rules = [
            // 昵称或者推荐码
            ['account', 'required|string'],
            // 密码
            ['password', 'required|string'],
            // 验证码
            //['captcha', 'required|string'],
        ];

        $params = $this->form->camelFormOrFail($rules);
       
        // 判断验证码是否正确
        // if ($params['captcha'] !== $_SESSION['info']) {
        //     return $this->form->error('验证码错误～');
        // }
          
        // 校验账号密码
        $user = User::where('nick_name', $params['account'])->orWhere('my_recommend_code', $params['account'])->first();
        if (!isset($user)) {
            return $this->form->error('昵称、编号或密码错误');
        }

        if ($params['password'] != Crypt::decryptString($user->password)) {
            return $this->form->error('昵称、编号或密码错误');
        }
        
        // 注入令牌
        $this->tokenService->init([
            'uid' => $user->id,
        ]);

        // 获取并更新令牌
        $token = $this->tokenService->updateToken([
            'uid' => $user->id,
        ]);
        $token->isActive = $user->is_active;
        return $this->form->getMessage($token);
    }

}